<!--
 @description
 @fileName Add.vue
 @author zengqiongying
 @created 2021/10/26 13:13:09
-->
<template>
  <inside-page fixed :titles="['内容管理',category.categoryName, detailData&&detailData.id?'编辑':'新增']" cancel-title="返回" @go-back="handleBack">
    <template slot="button">
      <el-button v-preventReClick v-loading="loading" size="mini" type="primary" @click="handleSave">保存</el-button>
    </template>
    <div v-loading="loading" style="margin-top:20px">
      <el-form ref="refForm" :rules="formRules" :model="formData" label-width="100px" size="small" :show-message="true" @submit.native.prevent="">
        <el-form-item label="内容名称：" prop="title">
          <el-input v-model="formData.title" maxlength="100" placeholder="请输入内容名称" show-word-limit @blur="formatContent('title')" />
        </el-form-item>
        <el-form-item label="内容概述：">
          <el-input
            v-model="formData.sketch"
            type="textarea"
            row="4"
            maxlength="300"
            placeholder="请输入概述"
            show-word-limit
            resize="none"
            class="c-form-summary"
            @blur="formatContent('sketch')"
          />
        </el-form-item>
        <el-form-item label="封面图：">
          <!-- prop="covers" -->
          <div class="cover-photo-list">
            <!-- <div v-for="(item,index) in coverPhotoList" :key="index" class="item-image">
              <el-image
                :src="item.fileUrl | filterImageUrl"
                fit="contain"
              />
              <div class="btn-del" @click.stop="handlePhotoDelete(index)">删除</div>
            </div> -->
            <qup-img-uploader
              ref="refUpload"
              :width="100"
              :height="100"
              mask
              :limit="5"
              :file-list="uploadImageList"
              @upload-success="uploadSuccess"
            />
          </div>
          <p style="color:#999">建议上传1M以内图片保证更佳显示效果。可上传五张封面图，第一张为主封面图。</p>
        </el-form-item>
        <el-form-item
          v-if="contentType===2"
          label="视频："
          prop="videoUrl"
          :rules="[{required:contentType===2,message:'请上传视频', trigger: 'change'}]"
        >
          <div class="video-container">
            <c-uploader
              btn-txt="上传视频"
              :width="200"
              :height="28"
              :view-width="500"
              :view-height="500"
              :image-size="400"
              :accept-type="['mp4','ogv']"
              file-type="video"
              :mask="false"
              :image-url="formData.videoUrl"
              :limit="1"
              @upload-success="uploadVideoSuccess"
              @remove="deleteVideoImage"
            />
            <span v-if="!formData.videoUrl" style="color:#999">视频大小限制400M,格式支持：mp4、ogv</span>
          </div>
        </el-form-item>
        <template v-if="contentType===1">
          <el-form-item
            label="内容："
            prop="content"
            :rules="[{required:contentType===1,message:'请上传内容', trigger: 'change'}]"
          >
            <!-- QupTinyEditor -->
            <div v-show="showContent">
              <TinyEditor
                ref="editor"
                v-model="htmlContent"
                :base-url="editorBaseUrl"
                :file-prefix="Img_prefix"
                uploda-req-field="multipartFile"
                upload-res-field="fileName"
                :upload-url="uploadUrl"
                :image-size="5"
                :video-accept="['mp4','ogv']"
                :custom-buttons="[]"
                :editor-config="editorConfig"
              />
            </div>
            <span class="btn-green" @click="showContent=!showContent">{{ showContent?'收起':'展开' }}内容</span>
          </el-form-item>
          <el-form-item label="附件：" prop="attachments">
            <div v-if="formData.attachData && formData.attachData.length" class="table-list-box">
              <el-table :data="formData.attachData" :max-height="500" style="width:100%">
                <el-table-column label="文件名称" prop="fileUrl">
                  <template v-slot="{row}">
                    <a :href="row.fileUrl | filterImageUrl" target="_banck" class="btn-green">{{ row.fileName || item.fileUrl }}</a>
                  </template>
                </el-table-column>
                <el-table-column label="是否开启水印" prop="isWatermark" width="150px">
                  <template v-slot="{row,$index}">
                    <el-form-item
                      :prop="`attachData.${$index}.isWatermark`"
                      :rules="[
                        {required:abelWaterTypes.includes(row.type),message:'必选',trigger:['change']}
                      ]"
                    >
                      <el-select v-model="row.isWatermark" :disabled="!abelWaterTypes.includes(row.type)" @change="handleChangeWaterMark(row)">
                        <el-option label="是" :value="1" />
                        <el-option label="否" :value="0" />
                      </el-select>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="密集程度" prop="watermarkDensity" width="150px">
                  <template v-slot="{row,$index}">
                    <el-form-item
                      :prop="`attachData.${$index}.watermarkDensity`"
                      :rules="[
                        {required:abelWaterTypes.includes(row.type) && row.isWatermark,message:'必选',trigger:['change']}
                      ]"
                    >
                      <el-select v-model="row.watermarkDensity" :disabled="!(abelWaterTypes.includes(row.type) && row.isWatermark)">
                        <el-option label="低" :value="1" />
                        <el-option label="中" :value="2" />
                        <el-option label="高" :value="3" />
                      </el-select>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="操作" prop="opt" width="80px">
                  <template v-slot="{row,$index}">
                    <el-button type="text" size="mini" class="btn-green" @click="handleDelAtt($index)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <p>
              <c-uploader
                btn-txt="上传附件"
                :width="200"
                :height="28"
                :image-size="400"
                file-type="file"
                :is-view="false"
                :mask="false"
                :limit="100"
                @upload-success="uploadFileSuccess"
              />
              <!-- :accept-type="['zip','rar','pdf','xls','xlsx','doc']" -->
              <span style="color:#999">文件大小限制400M</span>
            </p>

            <!--
              <el-button plain size="mini" @click.stop="openPicStock('file')">上传附件</el-button>
              <el-button plain size="mini" @click.stop="openPicStock('picture')">插入图片</el-button>
              <el-button plain size="mini" @click.stop="openPicStock('video')">插入视频</el-button>
              <el-button plain size="mini" @click.stop="openPicStock('audio')">插入音频</el-button>
            -->
          </el-form-item>
          <!-- <el-form-item label="附件：" prop="attachments">
            <div v-if="attachData && attachData.length>0" class="attach-box">
              <div v-for="(item,index) in attachData" :key="index" class="list">
                <div class="att-name">
                  <a :href="item.fileUrl | filterImageUrl" target="_banck">{{ item.fileName || item.fileUrl }}</a>
                </div>
                <div class="btn-down" @click="handleDelAtt(index)">删除</div>
              </div>
            </div>
          </el-form-item> -->
        </template>
      </el-form>
    </div>
  </inside-page>
</template>

<script>
import { fiterHtml, getImgsFromHtml } from '@/utils'
import BackPageMixin from '@/mixins/backPage'
import { saveContent } from '@/api/content'
import QupImgUploader from '@/components/imgUploader/multipleUpload'
import CUploader from '@/components/CUpload'
import TinyEditor from '@/components/tinyEditor' // 引入富文本
export default {
  name: 'ContentAddPage',
  components: {
    QupImgUploader,
    CUploader,
    TinyEditor
  },
  mixins: [BackPageMixin],
  props: {
    detailData: {
      type: [Object, String],
      default: ''
    },
    category: {
      type: [String, Object],
      default: ''
    }, // 类目ID
    contentType: {
      type: Number,
      default: 1
    } // 内容类型： 1 图文 / 2 视频
  },
  data() {
    return {
      editorBaseUrl: process.env.BASE_URL,
      Img_prefix: process.env.VUE_APP_Img_prefix,
      // uploadUrl: `${process.env.BASE_URL}api/v1/file/upload`,
      uploadUrl: `api/v1/file/upload`,

      editorConfig: {
        min_height: 600,
        resize: true,
        plugins: 'autoresize,autosave,image,axupimgs,media,link,table,fullscreen,preview,wordcount,emoticons,hr',
        toolbar: 'undo redo removeformat | cut copy paste | fontsizeselect forecolor backcolor | bold italic underline strikethrough |  image axupimgs media | alignleft alignright aligncenter alignjustify alignnone | outdent indent table | link unlink hr emoticons | fullscreen preview ',
        // content_css: 'ditor-content',
        imagetools_toolbar: 'imageoptions'
      },
      loading: false,
      htmlContent: '',
      formData: {
        title: '',
        sketch: '',
        covers: [],
        content: '',
        videos: [],
        videoUrl: '',
        state: 1,
        attachData: [],
        attachments: []
      },
      formRules: {
        title: [
          { required: true, message: '请输入', trigger: 'blur' }
        ]
        /* sketch: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        covers: [
          { required: true, message: '请上传', trigger: 'change' }
        ] */
      },
      coverPhotoList: [],
      videoList: [],
      showContent: true,
      abelWaterTypes: ['pdf', 'jpg', 'jpeg', 'png']// ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx'] // 可添加水印的类型
    }
  },

  computed: {
    defaultSummary() {
      return fiterHtml(this.htmlContent)
    },
    categoryId() {
      return (this.category && this.category.id) || ''
    },
    contentCount() {
      let count = 0
      count = this.defaultSummary.length
      return count
    },
    uploadImageList() {
      return this.coverPhotoList.map(v => {
        return {
          id: v.id,
          name: v.fileName,
          fileUrl: v.fileUrl,
          url: this.formatImageUrl(v.fileUrl)
        }
      })
    }
  },
  watch: {
    htmlContent(val, oldVal) {
      this.$set(this.formData, 'content', val)
    }
  },

  created() {
    if (this.detailData && this.detailData.id) {
      this.initFormData() // 初始化表单
    }
  },

  mounted() {

  },

  methods: {
    initFormData() {
      const data = this.detailData
      const covers = []
      data.covers && data.covers.forEach(v => {
        covers.push({
          fileUrl: v.fileUrl,
          fileName: v.fileName || '',
          id: v.id
        })
      })
      this.coverPhotoList = covers

      const videos = []
      data.videos && data.videos.forEach(v => {
        videos.push({
          fileUrl: v.fileUrl,
          fileName: v.fileName || '',
          id: v.id
        })
      })
      this.videoList = videos
      const videoUrl = videos.length === 0 ? '' : this.formatImageUrl(videos[0].fileUrl)

      const attachments = []
      data.attachments && data.attachments.forEach(v => {
        const type = v.type.toLowerCase()
        attachments.push({
          fileUrl: this.formatImageUrl(v.fileUrl),
          fileName: v.fileName || '',
          fileSize: v.fileSize || 0,
          id: v.id,
          type,
          isWatermark: this.abelWaterTypes.includes(type) ? [1, '1', 0, '0'].includes(v.isWatermark) ? v.isWatermark : '' : '',
          watermarkDensity: ['1', '2', '3', 1, 2, 3].includes(v.watermarkDensity) ? v.watermarkDensity : ''
        })
      })

      this.htmlContent = data.content || ''
      this.formData = {
        title: data.title,
        content: data.content || '',
        contentType: this.contentType,
        categoryId: this.categoryId,
        sketch: data.sketch,
        state: data.state,
        covers,
        videos,
        videoUrl,
        attachments,
        attachData: attachments
      }
    },
    // 封面图上传成功
    uploadSuccess(data) {
      /* if (data instanceof Array) {
        data.forEach(v => {
          const tmp = {
            id: v.id,
            fileName: v.sourceFileName || '',
            fileUrl: v.fileName
          }
          this.coverPhotoList.push(tmp)
        })
      } else {
        this.coverPhotoList.push({
          id: data.id,
          fileName: data.sourceFileName || '',
          fileUrl: data.fileName
        })
      } */
      /* this.coverPhotoList = data.map(v => {
        return {
          id: data.id,
          fileName: data.sourceFileName || '',
          fileUrl: data.fileName
        }
      })
      this.formData.covers = this.coverPhotoList
      this.$refs.refForm.validateField('covers') */
    },
    // 移除封面图片
    handlePhotoDelete(index) {
      this.coverPhotoList.splice(index, 1)
      this.formData.covers = this.coverPhotoList
      this.$refs.refForm.validateField('covers')
    },
    // 删除附件
    handleDelAtt(index) {
      this.formData.attachData.splice(index, 1)
    },
    formatContent(field) {
      let content = this.formData[field] || ''
      if (content) {
        content = fiterHtml(content)
      }
      this.$set(this.formData, field, content)
    },
    getParams() {
      this.coverPhotoList = this.$refs.refUpload.getAllImageList()
      const contentId = (this.detailData && this.detailData.id) || ''
      const covers = this.coverPhotoList.map(v => {
        return v
      })
      /* if (covers.length === 0) {
        const images = getImgsFromHtml(this.htmlContent)
        const defCoverUrl = (images && images[0]) || ''
        if (defCoverUrl) {
          covers.push({
            fileUrl: defCoverUrl
          })
        }
      } */

      let summary = fiterHtml(this.formData.sketch.trim())
      if (!summary) {
        summary = this.defaultSummary.slice(0, 60)
      }

      const attachments = this.formData.attachData.map(v => {
        let watermarkDensity = v.watermarkDensity || 0
        if (!v.isWatermark) {
          watermarkDensity = 0
        }
        return { ...v, ...{ watermarkDensity }}
      })

      let videos = []
      if (this.contentType === 2) {
        videos = this.videoList.map(v => {
          return v
        })
      }

      const title = fiterHtml(this.formData.title)

      const params = {
        categoryId: this.categoryId,
        contentType: this.contentType,
        title,
        sketch: summary,
        content: this.htmlContent,
        state: contentId ? this.detailData.state : 1,
        covers,
        videos,
        attachments
      }
      if (contentId) {
        params.id = contentId
      }
      return params
    },
    handleSave() {
      if (this.loading) return
      const images = getImgsFromHtml(this.htmlContent)
      if (this.contentType === 1 && this.contentCount === 0 && images.length === 0) {
        this.$message.warning('请输入内容')
        return
      }
      if (this.contentType === 2 && this.videoList.length === 0) {
        this.$message.warning('请上传视频')
        return
      }
      this.$refs['refForm'].validate((valid) => {
        if (valid) {
          const params = this.getParams()
          this.loading = true
          saveContent(params).then(res => {
            this.loading = false
            if (res.success === 1) {
              this.$message({
                message: `保存成功`,
                type: 'success'
              })
              this.$emit('success', !params.id)
              this.goBack()
            }
          }).catch(() => {
            this.loading = false
          })
        }
      })
    },
    handleBack() {
      this.$confirm(`当前操作未保存，是否保存后退出`, '提示', {
        distinguishCancelAndClose: true,
        confirmButtonText: '保存并退出',
        cancelButtonText: '直接退出',
        type: 'warning'
      }).then(() => {
        this.handleSave(0)
      }).catch(action => {
        // 直接退出
        if (action === 'cancel') {
          this.goBack()
        }
      })
    },
    // 视频上传成功
    uploadVideoSuccess(data) {
      this.$set(this.formData, 'videoUrl', data.sourceFileUrl)
      this.videoList = [{
        fileUrl: data.fileName,
        fileName: data.sourceFileName || '',
        id: data.id
      }]
      this.$refs.refForm.validateField('videoUrl')
    },
    // 移除已上传视频
    deleteVideoImage() {
      this.$set(this.formData, 'videoUrl', '')
      this.videoList = []
      this.$refs.refForm.validateField('videoUrl')
    },
    // 上传附件成功回调
    uploadFileSuccess(data) {
      const type = data.type.toLowerCase()
      this.formData.attachData.push({
        fileUrl: data.fileName,
        fileName: data.sourceFileName || '',
        fileSize: data.fileSize,
        id: data.id,
        type,
        isWatermark: this.abelWaterTypes.includes(type) ? '' : 0,
        watermarkDensity: ''
      })
    },
    handleChangeWaterMark(row) {
      if (row.isWatermark === 0 && row.watermarkDensity) {
        this.$set(row, 'watermarkDensity', '')
      }
    }
  }
}

</script>
<style lang='scss' scoped>

.cover-photo-list{
  display: flex;
  flex-wrap: wrap;
  .item-image{
    position: relative;
    width: 100px;
    height: 100px;
    margin-right: 10px;
    margin-bottom: 10px;
    border: 1px solid #d8d8d8;
    overflow: hidden;
    margin-bottom: 5px;
    .el-image{
      width: 98px;
      height: 98px;
    }
    .btn-del{
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
      line-height: 30px;
      background: rgba($color: #000000, $alpha: 0.5);
      color: #fff;
      text-align: center;
      visibility: hidden;
      cursor: pointer;
    }
    &:hover .btn-del{
      visibility:visible;
    }
  }
}
.c-form-summary{
 /deep/ .el-textarea__inner{
    height: 100px;
    line-height: 22px;
  }
}

.attach-box{
  padding: 10px;
  .list{
    display: flex;
    align-items: center;
    margin-bottom:10px;
    color: #3DC094;
    a{
      color: #3DC094;
    }
    .att-name{
      // min-width: 200px;
    }
    .btn-down{
      margin-left: 20px;
      color: #999;
      border:#cdcdcd 1px solid;
      width:40px;
      line-height:22px;
      border-radius:2px;
      text-align: center;
      text-decoration: none;
      cursor: pointer;
    }
  }
}
</style>
